using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Diagnostics;

namespace AvaAI批量点评系统.Services;

public class AudioService
{
    private bool _isRecording = false;
    private bool _isPlaying = false;
    private MemoryStream? _audioStream;

    public event EventHandler<string>? RecordingStatusChanged;
    public event EventHandler<string>? PlaybackStatusChanged;

    /// <summary>
    /// 开始录音
    /// </summary>
    public async Task<bool> StartRecordingAsync()
    {
        if (_isRecording)
        {
            return false;
        }

        try
        {
            _isRecording = true;
            _audioStream = new MemoryStream();
            
            RecordingStatusChanged?.Invoke(this, "🎙️ 录音已开始，请说话...");
            
            // 这里应该集成实际的音频录制库，比如NAudio
            // 目前先模拟录音过程
            await SimulateRecordingAsync();
            
            return true;
        }
        catch (Exception ex)
        {
            _isRecording = false;
            RecordingStatusChanged?.Invoke(this, $"录音启动失败: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 停止录音并返回音频数据
    /// </summary>
    public async Task<byte[]?> StopRecordingAsync()
    {
        if (!_isRecording)
        {
            return null;
        }

        try
        {
            _isRecording = false;
            RecordingStatusChanged?.Invoke(this, "🛑 录音已停止，正在处理音频数据...");

            if (_audioStream != null)
            {
                var audioData = _audioStream.ToArray();
                _audioStream.Dispose();
                _audioStream = null;
                
                RecordingStatusChanged?.Invoke(this, $"✅ 音频录制完成，大小: {audioData.Length} 字节");
                return audioData;
            }
            
            return null;
        }
        catch (Exception ex)
        {
            RecordingStatusChanged?.Invoke(this, $"录音停止失败: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// 播放音频数据
    /// </summary>
    public async Task<bool> PlayAudioAsync(byte[] audioData)
    {
        if (_isPlaying)
        {
            return false;
        }

        try
        {
            _isPlaying = true;
            PlaybackStatusChanged?.Invoke(this, "🔊 正在播放语音回复...");
            
            // 真正的音频播放实现
            await PlayAudioDataAsync(audioData);
            
            _isPlaying = false;
            PlaybackStatusChanged?.Invoke(this, "✅ 语音播放完成");
            return true;
        }
        catch (Exception ex)
        {
            _isPlaying = false;
            PlaybackStatusChanged?.Invoke(this, $"音频播放失败: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 保存音频数据到文件
    /// </summary>
    public async Task<string> SaveAudioToFileAsync(byte[] audioData, string fileName = "")
    {
        if (string.IsNullOrEmpty(fileName))
        {
            fileName = $"audio_{DateTime.Now:yyyyMMdd_HHmmss}.wav";
        }

        var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var audioFolder = Path.Combine(documentsPath, "AvaAI_Audio");
        
        if (!Directory.Exists(audioFolder))
        {
            Directory.CreateDirectory(audioFolder);
        }

        var filePath = Path.Combine(audioFolder, fileName);
        await File.WriteAllBytesAsync(filePath, audioData);
        
        return filePath;
    }

    /// <summary>
    /// 从文件加载音频数据
    /// </summary>
    public async Task<byte[]?> LoadAudioFromFileAsync(string filePath)
    {
        if (!File.Exists(filePath))
        {
            return null;
        }

        try
        {
            return await File.ReadAllBytesAsync(filePath);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 检查是否正在录音
    /// </summary>
    public bool IsRecording => _isRecording;

    /// <summary>
    /// 检查是否正在播放
    /// </summary>
    public bool IsPlaying => _isPlaying;

    /// <summary>
    /// 获取支持的音频格式
    /// </summary>
    public List<string> GetSupportedFormats()
    {
        return new List<string> { "wav", "mp3", "aac" };
    }

    /// <summary>
    /// 模拟录音过程（实际应用中需要替换为真实的录音实现）
    /// </summary>
    private async Task SimulateRecordingAsync()
    {
        // 这里应该实现真实的录音逻辑
        // 可以使用NAudio、System.Speech或其他音频库
        
        // 模拟录音数据（实际中这里会是从麦克风采集的音频）
        await Task.Delay(100); // 模拟初始化时间
        
        // 创建模拟的音频数据（WAV格式头部+音频数据）
        var sampleRate = 24000; // 24kHz采样率，与Omni模型匹配
        var channels = 1; // 单声道
        var bitsPerSample = 16; // 16位
        var duration = 3; // 模拟3秒录音
        
        var dataSize = sampleRate * channels * (bitsPerSample / 8) * duration;
        var fileSize = dataSize + 44; // WAV头部44字节
        
        // 创建WAV文件头
        var wavHeader = CreateWavHeader(fileSize, sampleRate, channels, bitsPerSample, dataSize);
        _audioStream?.Write(wavHeader, 0, wavHeader.Length);
        
        // 模拟音频数据（静音）
        var audioData = new byte[dataSize];
        _audioStream?.Write(audioData, 0, audioData.Length);
    }

    /// <summary>
    /// 真正的音频播放实现
    /// </summary>
    private async Task PlayAudioDataAsync(byte[] audioData)
    {
        try
        {
            // 使用临时文件播放音频（跨平台兼容方案）
            await PlayAudioViaTemporaryFile(audioData);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"播放音频失败: {ex.Message}");
            // 降级到模拟播放
            await SimulatePlaybackAsync(audioData);
        }
    }

    /// <summary>
    /// 通过临时文件播放音频（跨平台兼容方案）
    /// </summary>
    private async Task PlayAudioViaTemporaryFile(byte[] audioData)
    {
        var tempFile = Path.GetTempFileName();
        var audioFile = Path.ChangeExtension(tempFile, ".wav");
        
        try
        {
            // 写入临时文件
            await File.WriteAllBytesAsync(audioFile, audioData);
            
            // 检测操作系统并使用相应的播放命令
            string command;
            string arguments;
            
            if (OperatingSystem.IsWindows())
            {
                // Windows: 使用内置的音频播放
                command = "powershell";
                arguments = $"-Command \"(New-Object Media.SoundPlayer '{audioFile}').PlaySync()\"";
            }
            else if (OperatingSystem.IsLinux())
            {
                // Linux: 使用aplay或paplay
                command = "aplay";
                arguments = audioFile;
            }
            else if (OperatingSystem.IsMacOS())
            {
                // macOS: 使用afplay
                command = "afplay";
                arguments = audioFile;
            }
            else
            {
                // 其他系统：尝试使用系统默认程序打开
                command = audioFile;
                arguments = "";
            }
            
            // 启动播放进程
            var processInfo = new ProcessStartInfo
            {
                FileName = command,
                Arguments = arguments,
                UseShellExecute = OperatingSystem.IsWindows() && command == audioFile,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                RedirectStandardOutput = !OperatingSystem.IsWindows() || command != audioFile,
                RedirectStandardError = !OperatingSystem.IsWindows() || command != audioFile
            };
            
            using var process = Process.Start(processInfo);
            if (process != null)
            {
                // 估算播放时间（24kHz采样率，16位，单声道）
                var estimatedDuration = Math.Max(2, audioData.Length / 48000);
                
                // 等待播放完成或超时
                var completed = await Task.Run(() => process.WaitForExit(estimatedDuration * 1000 + 2000));
                
                if (!completed && !process.HasExited)
                {
                    try
                    {
                        process.Kill();
                    }
                    catch
                    {
                        // 忽略Kill失败
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"临时文件播放失败: {ex.Message}");
        }
        finally
        {
            // 异步清理临时文件，避免阻塞
            _ = Task.Run(async () =>
            {
                await Task.Delay(1000); // 等待播放完成
                try
                {
                    if (File.Exists(audioFile))
                    {
                        File.Delete(audioFile);
                    }
                    if (File.Exists(tempFile))
                    {
                        File.Delete(tempFile);
                    }
                }
                catch
                {
                    // 忽略清理错误
                }
            });
        }
    }



    /// <summary>
    /// 模拟音频播放过程（降级方案）
    /// </summary>
    private async Task SimulatePlaybackAsync(byte[] audioData)
    {
        // 估算播放时间（24kHz采样率，16位，单声道）
        var estimatedDuration = Math.Max(1, audioData.Length / 48000);
        await Task.Delay(estimatedDuration * 1000);
    }

    /// <summary>
    /// 创建WAV文件头
    /// </summary>
    private byte[] CreateWavHeader(int fileSize, int sampleRate, int channels, int bitsPerSample, int dataSize)
    {
        var header = new byte[44];
        var byteRate = sampleRate * channels * (bitsPerSample / 8);
        var blockAlign = channels * (bitsPerSample / 8);

        // RIFF header
        Array.Copy(System.Text.Encoding.ASCII.GetBytes("RIFF"), 0, header, 0, 4);
        Array.Copy(BitConverter.GetBytes(fileSize - 8), 0, header, 4, 4);
        Array.Copy(System.Text.Encoding.ASCII.GetBytes("WAVE"), 0, header, 8, 4);

        // fmt chunk
        Array.Copy(System.Text.Encoding.ASCII.GetBytes("fmt "), 0, header, 12, 4);
        Array.Copy(BitConverter.GetBytes(16), 0, header, 16, 4); // chunk size
        Array.Copy(BitConverter.GetBytes((short)1), 0, header, 20, 2); // audio format (PCM)
        Array.Copy(BitConverter.GetBytes((short)channels), 0, header, 22, 2);
        Array.Copy(BitConverter.GetBytes(sampleRate), 0, header, 24, 4);
        Array.Copy(BitConverter.GetBytes(byteRate), 0, header, 28, 4);
        Array.Copy(BitConverter.GetBytes((short)blockAlign), 0, header, 32, 2);
        Array.Copy(BitConverter.GetBytes((short)bitsPerSample), 0, header, 34, 2);

        // data chunk
        Array.Copy(System.Text.Encoding.ASCII.GetBytes("data"), 0, header, 36, 4);
        Array.Copy(BitConverter.GetBytes(dataSize), 0, header, 40, 4);

        return header;
    }

    public void Dispose()
    {
        _audioStream?.Dispose();
    }
} 